//
//  MHDownloadViewController.m
//  MHO
//
//  Created by papo on 4/12/14.
//  Copyright (c) 2014 maihoang. All rights reserved.
//

#import "MHDownloadViewController.h"
#import "MHNavibarView.h"
#import "MHAppDelegate.h"
#import "Contants.h"
#import "TTScrollSlidingPagesController.h"
#import "TTSlidingPage.h"
#import "TTSlidingPageTitle.h"
#import "Lib.h"
#import "DownloadCellTableViewCell.h"
#import "DownloadManager.h"
#import "DownloadDoneCell.h"


@interface MHDownloadViewController ()
{
//    BOOL
    NSMutableArray* installingArray, * installedArray, *updateArray;
    NSInteger       _indexPage;
}
@property (nonatomic, strong) MHNavibarView* naviBar;
@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIButton *installingButton;
@property (weak, nonatomic) IBOutlet UIButton *installedButton;
@property (weak, nonatomic) IBOutlet UIButton *updateButton;

@property (strong, nonatomic) TTScrollSlidingPagesController *mySlider;

@property (nonatomic, weak) IBOutlet UITableView* tableView;

@property (strong, nonatomic) IBOutlet UITableViewController *installingTableView;
@property (strong, nonatomic) IBOutlet UITableViewController *installedTableView;
@property (strong, nonatomic) IBOutlet UITableViewController *updateTableView;
@end

@implementation MHDownloadViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _naviBar = [MHNavibarView createWithLeftButton:nil rightButton:nil searchButton:YES];
    _naviBar.rightButton.hidden = YES;
    [_naviBar setActionSelectorDelegate:self left:@selector(leftButtonPressed:) right:nil search:nil];
    [self.naviBar setRootViewController:self];
    [self.view addSubview:_naviBar];

    //initial setup of the TTScrollSlidingPagesController.
    self.mySlider = [[TTScrollSlidingPagesController alloc] init];

    //set properties to customiser the slider. Make sure you set these BEFORE you access any other properties on the slider, such as the view or the datasource. Best to do it immediately after calling the init method.
    //self.slider.hideStatusBarWhenScrolling = YES;
    self.mySlider.titleScrollerHidden = YES;
    //slider.titleScrollerHeight = 100;
    //slider.titleScrollerItemWidth=60;
    //slider.titleScrollerBackgroundColour = [UIColor darkGrayColor];
    //slider.disableTitleScrollerShadow = YES;
    self.mySlider.disableUIPageControl = YES;
    //slider.initialPageNumber = 1;
    //slider.pagingEnabled = NO;
    //slider.zoomOutAnimationDisabled = YES;

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7){
        self.mySlider.hideStatusBarWhenScrolling = YES;//this property normally only makes sense on iOS7+. See the documentation in TTScrollSlidingPagesController.h. If you wanted to use it in iOS6 you'd have to make sure the status bar overlapped the TTScrollSlidingPagesController.
    }

    //set the datasource.
    self.mySlider.dataSource = self;
    self.mySlider.delegate = self;

    //add the slider's view to this view as a subview, and add the viewcontroller to this viewcontrollers child collection (so that it gets retained and stays in memory! And gets all relevant events in the view controller lifecycle)
    CGRect frame = self.view.frame;
    frame.origin.y += self.topView.frame.size.height ;
    frame.origin.y += self.naviBar.frame.size.height;
    frame.size.height -= self.topView.frame.size.height;
    frame.size.height -= self.naviBar.frame.size.height;
    self.mySlider.view.frame = frame;
    [self.view addSubview:self.mySlider.view];
    [self addChildViewController:self.mySlider];

//    [self installingButtonPressed:nil];

    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"DownloadDoneCell" bundle:nil] forCellReuseIdentifier:@"DownloadDoneCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"DownloadCellTableViewCell" bundle:nil] forCellReuseIdentifier:@"DownloadCell"];
//    [self refresh];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(needReloadTableViewWithObject:) name:kNotificationDownloadSuccess object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(needReloadTableViewWithObject:) name:kNotificationDownloadFailed object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(needReloadTableViewWithObject:) name:kNotificationRemoveDownload object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self refresh];
}

- (void)needReloadTableViewWithObject:(id)object {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self refresh];
    });
//    [self performSelector:@selector(test) withObject:nil afterDelay:1.0];
}

- (void)test {
    NSLog(@"testtt");
}

- (void)refresh {
    NSDictionary* dict = [[DownloadManager sharedManager] downloadDictionary];
    if (!self.data) {
        self.data = [NSMutableArray array];
    }
    if (!dict) {
        return;
    }
   
    [self.data removeAllObjects];
    NSArray* allKeys = [dict allKeys];
    for (NSString* key in allKeys) {
        NSDictionary* appDict = [dict objectForKey:key];
        if (appDict) {
            if (_indexPage == 0 && [[appDict objectForKey:@"finish"] boolValue] == NO) {
                [self.data addObject:appDict];
            }
            else if (_indexPage == 1 && [[appDict objectForKey:@"finish"] boolValue])
            {
                [self.data addObject:appDict];
            }
        }
    }
    
    [self.tableView reloadData];
}

- (void)leftButtonPressed:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - UITableViewSOurce
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.data.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 70;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //DownloadDoneCell
    NSString* cellIdentifier = @"DownloadCell";
    if (_indexPage == 1) {
        cellIdentifier = @"DownloadDoneCell";
    }
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        if (_indexPage==0) {
            cell = [DownloadCellTableViewCell cellFromNib];
        }
        else {
            cell = [[[NSBundle mainBundle] loadNibNamed:cellIdentifier owner:self options:nil] objectAtIndex:0];
        }
    }

    NSDictionary* appDict = self.data[indexPath.row];
    TCBlobDownloader* download = [[TCBlobDownloader alloc] init];
    Application* app = [[Application alloc] init];
    app.appName = [appDict objectForKey:@"appName"];
    app.file = [appDict objectForKey:@"file"];
    app.imagePath = [appDict objectForKey:@"icon"];
    app.plist = strCheckNull([appDict objectForKey:@"plist"]);
    download.app = app;
    download.totalDataLength = (uint64_t)[[appDict objectForKey:@"totalsize"] unsignedLongLongValue];
    download.receivedDataLength = 0;//(uint64_t)[[appDict objectForKey:@"receive"] unsignedLongLongValue];
    NSLog(@"download: total: %llu receive: %llu", download.totalDataLength, download.receivedDataLength);
    uint64_t fileSize = (uint64_t)[Lib sizeOfFile:[[TCBlobDownloadManager sharedInstance].defaultDownloadPath stringByAppendingPathComponent:[appDict objectForKey:@"path"]]];
    download.expectedDataLength = download.totalDataLength - fileSize;
    download.firstDataLength = fileSize;
    app.size = [NSString stringWithFormat:@"%lluMB", download.totalDataLength / 1024 / 1024];
    download.fileName = (NSString*)[appDict objectForKey:@"path"];
    NSLog(@"expected length: %llu size %llu", download.expectedDataLength, download.firstDataLength);
    
    if (_indexPage == 0) {
        DownloadCellTableViewCell* dCell = (DownloadCellTableViewCell*)cell;
        NSArray* listDownload = [DownloadManager sharedManager].listDownload;
        for (TCBlobDownloader* d in listDownload) {
            if ([d.app.appName isEqualToString:app.appName]) {
                download = d;
                break;
            }
        }
        if (dCell && download) {
            [dCell setDownload:download];
        }
    }
    else if (_indexPage == 1) {
        DownloadDoneCell* dCell = (DownloadDoneCell*)cell;
        if ([dCell isKindOfClass:[DownloadDoneCell class]]) {
            [dCell setApp:app];
        }
    }

    return cell;
}


#pragma mark - UITableViewDelegate 
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_indexPage == 1) {
        NSDictionary* appDict = self.data[indexPath.row];
        TCBlobDownloader* download = [[TCBlobDownloader alloc] init];
        Application* app = [[Application alloc] init];
        app.appName = [appDict objectForKey:@"appName"];
        app.file = [appDict objectForKey:@"file"];
        app.imagePath = [appDict objectForKey:@"icon"];
        download.app = app;
        download.totalDataLength = [[appDict objectForKey:@"totalsize"] unsignedLongLongValue];
        download.receivedDataLength = [[appDict objectForKey:@"receive"] unsignedLongLongValue];
        uint64_t fileSize = [Lib sizeOfFile:[[TCBlobDownloadManager sharedInstance].defaultDownloadPath stringByAppendingPathComponent:[appDict objectForKey:@"path"]]];
        download.expectedDataLength = download.totalDataLength - fileSize;
        download.totalDataLength = fileSize;
        download.fileName = (NSString*)[appDict objectForKey:@"path"];
        app.size = [NSString stringWithFormat:@"%lluMB", fileSize / 1024 / 1024];
        
        [Lib installApp:download];
    }
}


#pragma mark TTSlidingPagesDataSource methods
-(NSInteger)numberOfPagesForSlidingPagesViewController:(TTScrollSlidingPagesController *)source{
    return 3;
}

-(TTSlidingPage *)pageForSlidingPagesViewController:(TTScrollSlidingPagesController*)source atIndex:(NSInteger)index{
    UIViewController *viewController;
    if (index == 0) {
        viewController = self.installingTableView;
    }
    else if (index == 1) {
        viewController = self.installedTableView;
    }
    else {
        viewController = self.updateTableView;
    }
    CGRect frame = self.mySlider.view.frame;
    frame.origin.y = 0;
    //    frame.size.height -= self.topView.frame.size.height;
    [viewController.view setFrame:frame];

    return [[TTSlidingPage alloc] initWithContentViewController:viewController];
}

-(TTSlidingPageTitle *)titleForSlidingPagesViewController:(TTScrollSlidingPagesController *)source atIndex:(NSInteger)index{
    TTSlidingPageTitle *title;
    if (index == 0){
        //use a image as the header for the first page
        title= [[TTSlidingPageTitle alloc] initWithHeaderText:@"Top App"];
    } else {
        //all other pages just use a simple text header
        title = [[TTSlidingPageTitle alloc] initWithHeaderText:@"Top Game"];

    }
    return title;
}

////The below method in the datasource might get removed from the control some time in the future as it doesn't work that well with the headers if the width is small.
//-(int)widthForPageOnSlidingPagesViewController:(TTScrollSlidingPagesController *)source atIndex:(int)index
//{
//    if (index ==3){
//        return 130;
//    } else {
//        return self.view.frame.size.width;
//    }
//}

#pragma mark - delegate
-(void)didScrollToViewAtIndex:(NSUInteger)index
{
    if (index == 0) {
        //        self.tableView = self.topAppTableView.tableView;
        //        self.group = kGroupApp;
        [self installingButtonPressed:nil];
    }
    else if (index == 1){
        //        self.tableView = self.topGameTableView.tableView;
        //        self.group = kGroupGame;
        [self installedButtonPressed:nil];
    }
    else {
        [self updateButtonPressed:nil];
    }
    //    [self refresh];
}

- (IBAction)installingButtonPressed:(id)sender {
    [self.mySlider scrollToPage:0 animated:YES];
    [self.installingButton setEnabled:NO];
    [self.installedButton setEnabled:YES];
    [self.updateButton setEnabled:YES];

    self.tableView = self.installingTableView.tableView;
    _indexPage = 0;
    [self refresh];
}
- (IBAction)installedButtonPressed:(id)sender {
    [self.mySlider scrollToPage:1 animated:YES];
    [self.installingButton setEnabled:YES];
    [self.installedButton setEnabled:NO];
    [self.updateButton setEnabled:YES];

    self.tableView = self.installedTableView.tableView;
    _indexPage = 1;
    [self refresh];

}
- (IBAction)updateButtonPressed:(id)sender {
    [self.mySlider scrollToPage:2 animated:YES];
    [self.installingButton setEnabled:YES];
    [self.installedButton setEnabled:YES];
    [self.updateButton setEnabled:NO];

    self.tableView = self.updateTableView.tableView;
    _indexPage = 2;
    [self refresh];

}

@end
